import util from '../../../utils/utils';
import Dialog from '../../../dist/dialog/dialog';
import {
  CartHttp
} from '../../../api/cart.js'
const cartModel = new CartHttp();

import {
  UserHttp
} from '../../../api/user.js'
const userHttp = new UserHttp()

Page({
  /**
   * 页面的初始数据
   */
  payComponentEl: null,
  data: {
    orderInfo: {
      orderStatus: '',
    }, //订单详情内容
    orderNumber: '', //订单id
    deliverPhone: '', //快递员手机号
    isShowPayBox: false, //支付框
  },
  initPage: function(option) {
    if (option.id) {
      this.setData({
        orderNumber: option.id
      })
    } else {
      util.msg("订单号错误")
    }
    wx.hideShareMenu();
    this.httpGetOrderDetailr();
    this.payComponentEl = this.selectComponent('#payBox');
  },


  upAddress(_detail) {
    let self = this;
    setTimeout(function() {
      Dialog.confirm({
        message: '确定中奖物品邮寄到这个地址？',
        confirmButtonText: "立即提交",
        cancelButtonText: "我再选选"
      }).then(() => {
        util.request({
          url: '/order/updateGiftOrderAddress',
          loading: true,
          isJava: true,
          data: {
            unionOrderId: self.data.orderNumber,
            address: _detail.address,
            receiveName: _detail.user_name,
            phoneNumber: _detail.phone_number,
          },
          handle: true,
          callback: function(result) {
            if (result.status === 'ok') {
              util.msg('订单收货地址提交成功,请等待工作人员处理');
              setTimeout(function() {
                self.httpGetOrderDetailr();
              }, 300);
            } else {
              util.msg(result.msg);
            }
          },
          error: function(result) {
            if (result.msg) {
              util.msg(result.msg);
            } else {
              util.msg('未知错误！');
            }
          }
        });
      }).catch(() => {

      });
    }, 300);

  },
  getAddress: function(e) {
    let storeId = e.detail.storeId;
    util.toPage('/pages/me/address/manage/manage?store_id=' + storeId);
  },

  //取消订单
  httpOrderOff() {
    return userHttp.getOrderOff({
      unionOrderId: this.data.orderNumber
    }).then((res) => {
      this.httpGetOrderDetailr();
      wx.navigateBack({
        delta: 1
      });
    })
  },
  //申请售后退款
  httpOrderAfterSale() {
    return userHttp.getOrderAfterSale({
      orderNumber: this.data.orderNumber,
      reason: ""
    }).then((res) => {
      wx.navigateTo({
        url: 'orderRefund/orderRefund'
      });
      this.httpGetOrderDetailr();
    })
  },
  //打开支付的盒子
  openPayBox: function(order_id) {
    this.setData({
      isShowPayBox: true,
    });
    this.payComponentEl.switchPayment(this.data.paymentMethod);
    this.payComponentEl.setShowPayTime(false);
    this.payComponentEl.setOrderID(order_id);
    this.payComponentEl.openPayMethod();
  },
  payComplete: function(res) {
    let self = this;
    self.setData({
      isShowPayBox: false,
    });
    // if (res.detail.status === 'complete') {
    //   let url = '';
    //   url = '/pages/goods/paySuccess/paySuccess?id=' + self.data.orderNumber
    //   setTimeout(function() {
    //     util.toPage(url, false, true);
    //   }, 300);
    // }
    this.httpGetOrderDetailr();
  },

  // 获取订单信息
  httpGetOrderDetailr() {
    return userHttp.getOrderDetailr({
      orderNumber: this.data.orderNumber
    }).then((res) => {
      this.setData({
        orderInfo: this.formatData(res),
        deliverPhone: res.deliverPhone
      })
      wx.hideNavigationBarLoading();
      wx.stopPullDownRefresh();
    }).catch(err => {
      util.msg("网络错误,请检查后重试!")
      wx.navigateBack({
        delta: 1
      })

    })
  },
  //我要免单
  onFreeofCharge() {
    let token = wx.getStorageSync('token');
    let orderNumber = this.data.orderNumber;
    // PayPackMoney.html?token=60766_000000&orderNumber=1204303128078254080&others=true
    let url = util.pageUrl + "h5pages/PayPackMoney.html?others=true&token=" + token + '&orderNumber=' + orderNumber;
    wx.redirectTo({
      url: '/pages/index/web/index?itle=买单就反钱&url=' + encodeURIComponent(url),
      success: function(e) {
        console.log('去了我要免单');
      }
    });
  },
  //取消订单
  onCancelOrder() {
    let that = this;
    wx.showModal({
      title: '是否取消订单',
      // content: '是否取消订单',
      success: function(res) {
        if (res.confirm) {
          //如果订单状态是代付款则是直接取消
          if (that.data.orderInfo.orderStatus == 0) {
            that.httpOrderOff();
          } else {
            that.httpOrderRefund();
          }
        }
      }
    });
  },
  httpOrderRefund() {
    return userHttp.getOrderRefund({
      unionOrderId: this.data.orderNumber,
      reason: ""
    }).then((res) => {
      if (res == '退款成功') {
        util.msg("退款成功")
      }
      this.httpGetOrderDetailr();
    })
  },
  //申请售后
  onAfterSale() {
    let that = this;
    wx.showModal({
      title: '是否申请售后',
      // content: '是否申请售后',
      success: function(res) {
        if (res.confirm) {
          that.httpOrderAfterSale()
        }
      }
    })

  },
  //再买一单
  onAgain() {
    let orderId = this.data.orderNumber;
    let goods = [];
    let orderGoods = this.data.orderInfo.goodsInfo;
    let param = {
      storeId: this.data.orderInfo.storeId,
      dispatchType: 1,
      luckyBean: 0,
      payType: 4,
      goods: [],
    };
    for (let i = 0; i < orderGoods.length; i++) {
      goods.push({
        sku_id: orderGoods[i]['goodsSkuId'],
        spu_id: orderGoods[i]['goodsSpuId'],
        amount: orderGoods[i]['goodsNum'],
      });
      param['goods'].push({
        skuId: orderGoods[i]['goodsSkuId'],
        spuId: orderGoods[i]['goodsSpuId'],
        skuAmount: orderGoods[i]['goodsNum']
      });
    }
    util.toPage('/pages/goods/pendingOrder/pendingOrder?id=' + JSON.stringify(goods) + '&storeId=' + this.data.orderInfo.storeId + '&serviceId=' + this.data.orderInfo.storeServiceId);
  },
  //支付
  onPay() {
    this.openPayBox(this.data.orderInfo.fatherOrderId);

  },
  //联系配送员
  onContactExpress() {
    if (this.data.deliverPhone) {
      wx.makePhoneCall({
        phoneNumber: this.data.deliverPhone,
      })
    } else {
      util.msg("还未开始配送或已配送完成!")
    }

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {
    wx.showNavigationBarLoading();
    this.httpGetOrderDetailr();
  },

  //格式化数据
  formatData(res) {
    let img = util.pageUrl + 'mini/images/order/'
    res['isShowClock'] = false;
    res['statusDesc'] = res['orderStatusDesc'];
    res['isShowDeliverBtn'] = false
    //先判断订单类型
    //待付款状态
    if (res['orderStatus'] === 0) {
      res['imgurl'] = img + 'order4.png'
      res['imgcss'] = 'top-img-wait'
      res['statusDesc'] = '等待支付';
      res['statusDescText'] = '越早支付，越早送达，请尽快支付吧，超过30分钟订单自动取消';
      let stime = 30 * 60 * 1000 - (Date.parse(new Date()) - res.creatTime * 1000);
      res['sTime'] = stime > 0 ? stime : 0;
      res['isShowClock'] = stime > 0 ? true : false;
      res['topTitleText'] = '剩余支付时间';
      res['timeFormat'] = 'mm:ss';
      res['orderRealPayPrice'] = res['orderNeedPay'];
    }
    // 已支付状态
    if (res['orderStatus'] === 1) {
      res['imgurl'] = '/images/order/orderWaiting.png'
      res['imgcss'] = 'top-img-business'
      res['statusDesc'] = '已支付，等待商家接单…';
      res['topTitleText'] = '商家正在处理中';
      res['statusDescText'] = '请耐心等待，商家正在处理中…';
    }
    // 取消
    if (res['orderStatus'] === 2) {

    }
    if (res['orderMainType'] === 1 && res['deliverNo'] != null) {
      //正在配送
      if (res['orderStatus'] === 11) {
        res['imgurl'] = '/images/order/order_box.png'
        res['imgcss'] = 'top-img-delivery'
        res['statusDesc'] = '已寄出，请注意查收';
        res['topTitleText'] = '您的货物已寄出，请及时查收';
        res['statusDescText'] = '物流公司：' + res['deliverName'];
        res['statusDescText2'] = '快递单号：' + res['deliverNo'];
      }
      //正在配送
      if (res['orderStatus'] === 3) {
        res['imgurl'] = img + 'order2.png'
        res['imgcss'] = 'top-img-ok'
        res['statusDesc'] = '订单已完成';
        res['topTitleText'] = '您的订单已完成';
        res['statusDescText'] = '如有售后问题，请您联系商家处理。如联系不上商家或商家拒绝处理，请联系平台客服协助处理（客服入口-【我的】）';
      }
      res['isShowDeliverBtn'] = true
    } else if (res['orderMainType'] === 2) {
      if (res['orderStatus'] === 1) {
        res['imgurl'] = util.pageUrl + 'mini/images/order/winning_delivery.png'
        res['imgcss'] = 'top-img-winning-delivery'
        res['statusDesc'] = '等待客服给您寄出';
        res['topTitleText'] = '客服将尽快处理您的中奖信息';
        res['statusDescText'] = '客服已收到您的中奖信息，将尽快处理您的该笔信息';
      }
    } else {
      // 商家配货中
      if (res['orderStatus'] === 12 || res['orderStatus'] === 15) {
        res['imgurl'] = img + 'order1.png'
        res['imgcss'] = 'top-img-distribution'
        res['statusDesc'] = '商家正在配货中...';
        res['topTitleText'] = '您的货物商家正在为你配货';
        res['statusDescText'] = '请耐心等待，商家正在为您配货您的商品';
      }
      //正在配送
      if (res['orderStatus'] === 3 || res['orderStatus'] === 11) {
        res['imgurl'] = img + 'order3.png'
        res['imgcss'] = 'top-img-delivery'
        res['statusDesc'] = '配送员正在为您配送中…';
        res['statusDescText'] = '请耐心等待，配送员正在火速赶往你';
        let stime = res.receiveTime * 1000 - Date.parse(new Date());
        res['sTime'] = stime > 0 ? stime : 0;
        res['timeFormat'] = stime > 3600 * 1000 ? 'HH:mm:ss' : 'mm:ss';
        res['isShowClock'] = true;
        res['topTitleText'] = stime > 0 ? '预计送达时间' : '已超时';
      }
    }

    if (res['payChannelDesc'] === null) {
      res['payChannelDesc'] = '无'
    }
    //必须放在 res['receiveTime'] = '已送达'之前
    res['receiveTime'] = res['receiveTime'] === 0 ? '暂无' : util.formatTime('yyyy-MM-dd HH:mm:ss', res['receiveTime']);

    //完成
    if (res['orderStatus'] === 4 || res['orderStatus'] === 10) {
      res['imgurl'] = img + 'order2.png'
      res['imgcss'] = 'top-img-ok'
      if (res['orderStatus'] === 4) {
        res['statusDesc'] = '订单已完成';
      } else {
        res['statusDesc'] = '订单已收货';
      }
      res['topTitleText'] = '您的订单已完成';
      res['receiveTime'] = '已送达';
      res['statusDescText'] = '如有售后问题，请您联系商家处理。如联系不上商家或商家拒绝处理，请联系平台客服协助处理（客服入口-【我的】）';
    }
    //部分提货
    if (res['orderStatus'] === 5) {


    }
    //已完成-退款  已完成-退款部分
    if (res['orderStatus'] === 6 || res['orderStatus'] === 7) {
      res['imgurl'] = img + 'order2.png'
      res['imgcss'] = 'top-img-ok'
      res['statusDesc'] = '订单已退款';
      res['topTitleText'] = '您的订单已退款';
      res['statusDescText'] = '如有售后问题，请您联系商家处理。如联系不上商家或商家拒绝处理，请联系平台客服协助处理（客服入口-【我的】）';
    }



    if (res['orderStatus'] === 8 || res['orderStatus'] === 9 || res['orderStatus'] === 14) {
      res['imgurl'] = img + 'order2.png'
      res['imgcss'] = 'top-img-ok'
      res['statusDesc'] = '订单售后中';
      res['topTitleText'] = '您的订单正在售后';
      res['statusDescText'] = '如有售后问题，请您联系商家处理。如联系不上商家或商家拒绝处理，请联系平台客服协助处理（客服入口-【我的】）';
    }

    //售后申请审核
    if (res['orderStatus'] === 14) {
      res['imgurl'] = img + 'order2.png'
      res['imgcss'] = 'top-img-ok'
      res['topTitleText'] = '您的订单已完成';
      res['receiveTime'] = '已送达';
      res['statusDescText'] = '如有售后问题，请您联系商家处理。如联系不上商家或商家拒绝处理，请联系平台客服协助处理（客服入口-【我的】）';
    }
    //商家已拒绝
    if (res['orderStatus'] === 16) {
      res['imgurl'] = '/images/icon/notify_no.png'
      res['imgcss'] = 'top-img-refuse'
      res['statusDesc'] = '订单未接单';
      res['topTitleText'] = '您的订单商家未接';
      res['statusDescText'] = ' 您的金额已退款至原支付账户，请您注意查收';
    }
    //退款打回
    if (res['orderStatus'] === 17) {
      res['imgurl'] = img + 'order2.png'
      res['imgcss'] = 'top-img-ok'
      res['statusDesc'] = '退款打回';
      res['topTitleText'] = '您的订单退款申请已被商家拒绝';
      res['statusDescText'] = '如您仍有疑问可以申请仲裁处理';
    }

    // 商家配货中
    if (res['orderStatus'] === 18) {
      res['imgurl'] = '/images/order/no_perfect.png'
      res['imgcss'] = 'top-img-no-perfect'
      res['statusDesc'] = '订单信息尚未完善';
      res['topTitleText'] = '请尽快完善订单信息，以便给您发放奖励';
      res['statusDescText'] = '点击我要领奖进行信息完善';
      res['receiveTime'] = '暂无';
    }
    // 商家配货中
    if (res['orderStatus'] === 19) {
      res['imgurl'] = img + 'order2.png'
      res['imgcss'] = 'top-img-ok'
      res['statusDesc'] = '订单仲裁中';
      res['topTitleText'] = '您的订单正在仲裁';
      res['statusDescText'] = '如您有任何疑问请随时联系我们';
    }



    return res;
  },

  //跳转到商店
  goToStore() {
    wx.navigateTo({
      url: '/pages/store/index/store?id=' + this.data.orderInfo.storeId
    })
  }

});
